package change

import (
	"encoding/json"
	"game_server/framework/global"
	"game_server/framework/message"
	"game_server/framework/task"
	"game_server/game"
	"game_server/game/model"
	"game_server/proto"
	"github.com/duke-git/lancet/v2/convertor"
)

type AreaChangeReq struct {
	Area int `json:"area"`
}

func AreaChangeHandler(taskWrapper *task.TaskWrapper) *task.TaskWrapper {
	defer func() {
		err := recover()
		if err != nil {
			global.Logger.Errorf("err:%v", err)
		}
	}()
	defer global.Logger.Info("package:[change]:::function:[AreaChangeHandler]<======")
	global.Logger.Infof("======>package:[change]:::function:[AreaChangeHandler]:::id:%v", taskWrapper.ReceiverId)
	userId := taskWrapper.ReceiverId
	areaChangeReq := &AreaChangeReq{}
	json.Unmarshal([]byte(convertor.ToString(taskWrapper.MessageWrapper.Data)), areaChangeReq)
	var roomInfo *model.RoomInfo = nil
	for _, v := range game.GameManagerInstance().RoomInfos {
		_, ok := v.PlayerInfos.Get(userId)
		if ok {
			roomInfo = v
			break
		}
	}
	if roomInfo == nil {
		return nil
	}
	if roomInfo.Status != model.WAITING_BET {
		return nil
	}
	if roomInfo.Countdown <= 1 {
		return nil
	}
	playerInfo, ok := roomInfo.PlayerInfos.Get(taskWrapper.ReceiverId)
	if !ok {
		return nil
	}
	betInfo, ok := roomInfo.BetInfos.Get(playerInfo.Id)
	if !ok {
		return nil
	}
	betInfo.RoomArea = areaChangeReq.Area
	betInfoRes := &proto.BetInfoRes{}
	convertor.CopyProperties(betInfoRes, betInfo)

	messageWrapper := &message.MessageWrapper{Code: proto.AREACHANGE, Data: betInfoRes}
	task := &task.TaskWrapper{
		ReceiverId:     taskWrapper.ReceiverId,
		MessageWrapper: messageWrapper,
		SenderIds:      []int64{taskWrapper.ReceiverId},
	}
	return task
}
